import React, { useState, useEffect, useRef } from 'react';
import { useDrag } from 'react-dnd';
import { Card, Input, Tabs, Empty, Badge, Tooltip } from 'antd';
import { 
  TableOutlined, 
  FormOutlined, 
  SearchOutlined, 
  CalendarOutlined,
  CheckOutlined,
  AppstoreOutlined,
  LayoutOutlined,
  PictureOutlined,
  FontSizeOutlined,
  DashOutlined,
  BarChartOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import { ComponentType, ComponentCategory } from '../types/component';
import { 
  getAllComponents, 
  getComponentsByCategory, 
  initializeComponentRegistry,
  type ExtendedComponentDefinition 
} from './componentRegistry';
import './ComponentPalette.css';

// 组件类型到图标的映射
const componentIconMap: Record<string, React.ReactNode> = {
  [ComponentType.TABLE]: <TableOutlined />,
  [ComponentType.FORM]: <FormOutlined />,
  [ComponentType.INPUT]: <SearchOutlined />,
  [ComponentType.SELECT]: <SearchOutlined />,
  [ComponentType.DATE_PICKER]: <CalendarOutlined />,
  [ComponentType.CHECKBOX]: <CheckOutlined />,
  [ComponentType.RADIO]: <CheckOutlined />,
  [ComponentType.BUTTON]: <SearchOutlined />,
  [ComponentType.CONTAINER]: <AppstoreOutlined />,
  [ComponentType.GRID]: <AppstoreOutlined />,
  [ComponentType.TABS]: <LayoutOutlined />,
  [ComponentType.IMAGE]: <PictureOutlined />,
  [ComponentType.TEXT]: <FontSizeOutlined />,
  [ComponentType.DIVIDER]: <DashOutlined />,
  [ComponentType.CHART]: <BarChartOutlined />,
  [ComponentType.LIST]: <FileTextOutlined />,
  [ComponentType.SEARCH_BAR]: <SearchOutlined />,
  [ComponentType.LAYOUT]: <LayoutOutlined />,
  [ComponentType.DISPLAY]: <PictureOutlined />,
  [ComponentType.CUSTOM]: <AppstoreOutlined />
};

// 分类到标题的映射
const categoryTitleMap: Record<string, string> = {
  [ComponentCategory.BASIC]: '基础组件',
  [ComponentCategory.FORM]: '表单组件',
  [ComponentCategory.DATA]: '数据组件',
  [ComponentCategory.DATA_DISPLAY]: '数据展示',
  [ComponentCategory.LAYOUT]: '布局组件',
  [ComponentCategory.ACTION]: '操作组件',
  [ComponentCategory.ADVANCED]: '高级组件',
  [ComponentCategory.OTHERS]: '其他组件'
};

// 组件项
interface ComponentItemProps {
  component: ExtendedComponentDefinition;
}

const ComponentItem: React.FC<ComponentItemProps> = ({ component }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'component',
    item: { 
      type: component.type,
      name: component.name,
      defaultLayout: component.defaultLayout
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }), [component]);

  // 连接拖拽和ref
  drag(ref);

  return (
    <div 
      ref={ref} 
      className={`component-item ${isDragging ? 'component-item-dragging' : ''}`}
    >
      <Card size="small" styles={{ body: { padding: 0 } }}>
        <div className="component-item-content">
          <div className="component-item-icon">
            {componentIconMap[component.type] || <AppstoreOutlined />}
          </div>
          <div className="component-item-info">
            <div className="component-item-name">{component.title}</div>
            <div className="component-item-desc">{component.description || '拖拽到画布使用'}</div>
          </div>
        </div>
      </Card>
    </div>
  );
};

// 组件分类
interface ComponentCategoryProps {
  title: string;
  components: ExtendedComponentDefinition[];
}

const ComponentCategorySection: React.FC<ComponentCategoryProps> = ({ title, components }) => {
  if (!components || components.length === 0) return null;
  
  return (
    <div className="component-category">
      <div className="component-category-title">{title}</div>
      {components.map((component) => (
        <ComponentItem key={component.type} component={component} />
      ))}
    </div>
  );
};

const ComponentPalette: React.FC = () => {
  const [components, setComponents] = useState<ExtendedComponentDefinition[]>([]);
  const [filteredComponents, setFilteredComponents] = useState<ExtendedComponentDefinition[]>([]);
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('all');

  // 初始化组件
  useEffect(() => {
    initializeComponentRegistry();
    const allComponents = getAllComponents();
    setComponents(allComponents);
    setFilteredComponents(allComponents);
  }, []);

  // 搜索组件
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchText(value);
    
    if (!value) {
      setFilteredComponents(components);
      return;
    }
    
    const filtered = components.filter(
      (item) => 
        item.title.toLowerCase().includes(value.toLowerCase()) || 
        (item.description && item.description.toLowerCase().includes(value.toLowerCase()))
    );
    
    setFilteredComponents(filtered);
  };

  // 按分类过滤组件
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    
    if (key === 'all') {
      setFilteredComponents(
        searchText ? 
          components.filter(
            (item) => 
              item.title.toLowerCase().includes(searchText.toLowerCase()) || 
              (item.description && item.description.toLowerCase().includes(searchText.toLowerCase()))
          ) : 
          components
      );
      return;
    }
    
    const categoryComponents = getComponentsByCategory(key);
    
    setFilteredComponents(
      searchText ? 
        categoryComponents.filter(
          (item) => 
            item.title.toLowerCase().includes(searchText.toLowerCase()) || 
            (item.description && item.description.toLowerCase().includes(searchText.toLowerCase()))
        ) : 
        categoryComponents
    );
  };

  // 按分类分组组件
  const groupedComponents: Record<string, ExtendedComponentDefinition[]> = {};
  filteredComponents.forEach((component) => {
    const category = component.category;
    if (!groupedComponents[category]) {
      groupedComponents[category] = [];
    }
    groupedComponents[category].push(component);
  });

  // 获取分类数量
  const getCategoryCount = (category: string) => {
    return components.filter(item => item.category === category).length;
  };

  // 创建 Tabs 的 items 配置
  const tabItems = [
    {
      key: 'all',
      label: (
        <Tooltip title="所有组件">
          <Badge count={components.length} size="small">
            <span>全部</span>
          </Badge>
        </Tooltip>
      )
    },
    {
      key: ComponentCategory.BASIC,
      label: (
        <Tooltip title="基础组件">
          <Badge count={getCategoryCount(ComponentCategory.BASIC)} size="small">
            <span>基础</span>
          </Badge>
        </Tooltip>
      )
    },
    {
      key: ComponentCategory.FORM,
      label: (
        <Tooltip title="表单组件">
          <Badge count={getCategoryCount(ComponentCategory.FORM)} size="small">
            <span>表单</span>
          </Badge>
        </Tooltip>
      )
    },
    {
      key: ComponentCategory.DATA,
      label: (
        <Tooltip title="数据组件">
          <Badge count={getCategoryCount(ComponentCategory.DATA)} size="small">
            <span>数据</span>
          </Badge>
        </Tooltip>
      )
    },
    {
      key: ComponentCategory.LAYOUT,
      label: (
        <Tooltip title="布局组件">
          <Badge count={getCategoryCount(ComponentCategory.LAYOUT)} size="small">
            <span>布局</span>
          </Badge>
        </Tooltip>
      )
    }
  ];

  return (
    <div className="component-palette">
      <div className="component-palette-header">
        <Input
          placeholder="搜索组件"
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={handleSearch}
          allowClear
          className="component-palette-search"
        />
        
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          size="small"
          tabBarStyle={{ marginBottom: 8 }}
          items={tabItems}
        />
      </div>

      {/* 组件内容 */}
      <div className="component-palette-content">
        {filteredComponents.length > 0 ? (
          Object.entries(groupedComponents).map(([category, comps]) => (
            <ComponentCategorySection 
              key={category}
              title={categoryTitleMap[category] || category}
              components={comps}
            />
          ))
        ) : (
          <Empty description="未找到组件" />
        )}
      </div>
    </div>
  );
};

export default ComponentPalette;